<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>首页 - 管理界面</title>
    <style>
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        .dashboard {
            margin-bottom: 2rem;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 2rem;
            margin-top: 1rem;
        }

        .stat-card {
            background-color: #fff;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .stat-card h3 {
            margin-bottom: 1rem;
            color: #333;
        }

        .main-content {
            background-color: #fff;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        .table th,
        .table td {
            padding: 0.75rem;
            border: 1px solid #dee2e6;
        }

        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
        }

        .status-overload {
            color: #dc3545;
            font-weight: 600;
        }

        .status-idle {
            color: #28a745;
            font-weight: 600;
        }

        .btn {
            display: inline-block;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            text-decoration: none;
            cursor: pointer;
            border: none;
            font-size: 1rem;
        }

        .btn-primary {
            background-color: #007bff;
            color: white;
        }

        .alert {
            padding: 1rem;
            margin-bottom: 1rem;
            border-radius: 4px;
        }

        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        @media (max-width: 768px) {
            .stats {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="main-content">
            <div class="section-header">
                <h2>主机调动状态</h2>
                <button onclick="refresh()" class="btn btn-primary">刷新</button>
            </div>
            
            <div id="statusList"></div>
        </div>
    </div>

    <script>
        // 获取状态列表
        async function fetchStatusList() {
            try {
                const response = await fetch('/api/status', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    credentials: 'include'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                if (data.status === 'success') {
                    displayStatusList(data.data);
                } else {
                    showError(data.message || '获取状态列表失败');
                }
            } catch (error) {
                // 捕获 fetch 错误或上面抛出的错误
                console.error('获取状态列表失败:', error);
                // 检查错误消息是否包含 401 或响应状态为 401，如果是，可以给出更具体的提示
                let errorMessage = '获取状态列表失败，请检查网络连接';
                if (error.message && error.message.includes('401')) {
                     errorMessage = '获取状态列表失败：未授权或会话已过期，请尝试重新登录。';
                } else if (error instanceof Response && error.status === 401) { // 如果 fetch 自身抛出 Response 对象
                     errorMessage = '获取状态列表失败：未授权或会话已过期，请尝试重新登录。';
                } else if (error instanceof Error && error.message.includes('Failed to fetch')){
                     errorMessage = '获取状态列表失败：无法连接到服务器。';
                }
                // 避免重复显示错误消息
                const existingAlert = document.querySelector('.main-content .alert-danger');
                if (!existingAlert || !existingAlert.textContent.includes('未授权')) {
                    showError(errorMessage);
                }
            }
        }

        // 显示状态列表
        function displayStatusList(statuses) {
            const statusList = document.getElementById('statusList');
            if (!statuses || statuses.length === 0) {
                statusList.innerHTML = '<div class="alert alert-info">当前无主机调动状态</div>';
                return;
            }

            const table = document.createElement('table');
            table.className = 'table';
            
            // 表头
            const thead = document.createElement('thead');
            thead.innerHTML = `
                <tr>
                    <th>模块ID</th>
                    <th>子模块ID(cmdid)</th>
                    <th>IP</th>
                    <th>Port</th>
                    <th>调用者</th>
                    <th>成功次数</th>
                    <th>失败次数</th>
                    <th>操作时间</th>
                    <th>状态</th>
                </tr>
            `;
            table.appendChild(thead);
            
            // 表格内容
            const tbody = document.createElement('tbody');
            statuses.forEach(status => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${status.modid}</td>
                    <td>${status.cmdid}</td>
                    <td>${status.ip}</td>
                    <td>${status.port}</td>
                    <td>${status.caller}</td>
                    <td>${status.success_count}</td>
                    <td>${status.error_count}</td>
                    <td>${new Date(status.timestamp * 1000).toLocaleString()}</td>
                    <td class="${status.is_overload ? 'status-overload' : 'status-idle'}">
                        ${status.is_overload ? '超载' : '空闲'}
                    </td>
                `;
                tbody.appendChild(tr);
            });
            table.appendChild(tbody);
            
            statusList.innerHTML = '';
            statusList.appendChild(table);
        }

        // 显示错误消息
        function showError(message) {
            const alert = document.createElement('div');
            alert.className = 'alert alert-danger';
            alert.textContent = message;
            document.querySelector('.main-content').insertBefore(alert, document.getElementById('statusList'));
            setTimeout(() => alert.remove(), 3000);
        }

        // 刷新页面
        function refresh() {
            fetchStatusList();
        }

        // 页面加载时获取状态列表
        document.addEventListener('DOMContentLoaded', fetchStatusList);
        
        // 自动刷新（每5秒）
        setInterval(fetchStatusList, 5000);
    </script>
</body>
</html>
